﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;
using System.Windows.Threading;
using System.Windows;
using Project_CFT2;
using Multitouch;



namespace Project_CFT2.RFID
{
    /// <summary>
    /// This class handles the RFID interfacing to TI Low Frequency Evaluation Kit Series 2000 with methods.  public methods can be called externally
    /// </summary>
    class RfidAuth
    {
        #region class variable declarations
        bool Debug = true;

        
        

        

      
        
        //COM port settings
        const string DefaultComPort = "COM5";
        const int DefaultBaudRate = 9600;
        const int DefaultBufferSize = 80;
        const int DefaultInterval = 200; //0.2•b

        //Itemholder to store itmes to be looked up.... may not be required if database small
        //Hashtable itemHolder = new Hashtable();

        //RFID comms
        RFIDComm rfid = null;
        byte[] txBytes;

        Thread rxThread = null;

        long lastId = -1;
        //ID
        bool removeFlag = true;


        #endregion


        #region public functions

        public object WinRef
        {
            get;
            set;
        }

        //this is the delegate installation
        showPopup ShowP = new showPopup(MainWindow.showFurnitureAddedPopup);
        showMemberPopup ShowMemberP = new showMemberPopup(Window3.memberLogin);

        public void StartListening(bool DebugIn, object main)
        {
            WinRef = main;
            Debug = DebugIn;
            rfid = new RFIDComm(DefaultComPort, DefaultBaudRate);
            txBytes = new byte[DefaultBufferSize];
            OpenPort();
            SendCommand(IdTx.ReadLine);

        }

        public void StopListening()
        {
            SendCommand(IdTx.Read);
            ClosePort();

            if (rxThread != null)
            {
                rxThread.Abort();
            }


        }
        #endregion

        #region private functions

        //Handle readin of RFID .. what actions to perform.
        void DealEvent(long id)
        {
            //ID‚ª0‚Ìê‡‚Í‰æ‘œ•\Ž¦‚ð‚â‚ß‚éD
            if (id == 0)
            {
                Console.WriteLine("ID out is 0");
                //if (form != null)
                //    form.Dispose();
            }
            else
            {

                //‚±‚±‚ÉIDŒŸoŽž‚És‚¢‚½‚¢ˆ—‚ð‹LqD

                //–¢“o˜^‚ÌID‚Ìê‡CƒtƒH[ƒ€‚ªŠJ‚¢‚½‚ç•Â‚¶‚é

            }
            return;
        }

        //manipuluates byte returned
        private byte[] ChopBytes(byte[] bytes)
        {
            int cnt = 0;
            byte[] choppedBytes;
            for (int i = bytes.Length; i > 0; i--)
            {
                if (bytes[i - 1] == 0x00)
                {
                    cnt++;
                }
                else
                {
                    break;
                }
            }

            choppedBytes = new byte[bytes.Length - cnt];
            Array.Copy(bytes, 0, choppedBytes, 0, bytes.Length - cnt);

            return choppedBytes;
        }
        #endregion

        #region RFIDComm
        //COM interact with RFIDComm class
        void OpenPort()
        {
            if (rfid.IsOpen)
            {
                
                Console.WriteLine("Opened: " + rfid.Port);
                
            }
            else
            {
                if (rfid.Open())
                {
                    Console.WriteLine("Opening: " + rfid.Port);
                    if (rxThread == null)
                    {
                        rxThread = new Thread(new ThreadStart(ReadIdWorker));
                        rxThread.Start();
                    }
      
                }
                else
                {
                    Console.WriteLine("Port not opened: " + rfid.Port);
                }
            }
        }

        //COM closing
        void ClosePort()
        {
            if (rfid.IsOpen)
            {
                SendCommand(IdTx.Read);
                rfid.Close();
                if (rxThread != null && rxThread.IsAlive)
                {
                    rxThread.Abort();
                    rxThread = null;
                }
                Console.WriteLine("Port closed: " + rfid.Port);

            }
            else
            {
                Console.WriteLine("Unable to close port:" + rfid.Port);
            }
            return;
        }




        //Not sure what this does, but it is important
        void SendCommand(IdTx id)
        {
            byte[] data = new byte[1];
            SendCommand(id, data);
            return;
        }

        //(ˆê‰ñ“Ç‚ÝŽæ‚èC˜A‘±“Ç‚ÝŽæ‚è)C‘‚«ž‚Ý‚ÌƒRƒ}ƒ“ƒh‚ð‘—‚é
        void SendCommand(IdTx idType, byte[] data)
        {
            if (!(rfid.IsOpen))
            {
                Console.WriteLine("Port is not opened, unabled to read: " + rfid.Port);
                return;
            }

            if (rfid.SendMessage(idType, data, ref txBytes))
            {

                
                Console.WriteLine("ID read is: " + BitConverter.ToString(txBytes));
                if (idType == IdTx.ReadLine)
                {

                }
                else
                {

                }
            }
            else
            {
                Console.WriteLine("RFID Read error: " + BitConverter.ToString(txBytes));
            }
        }


        //˜A‘±“Ç‚ÝŽæ‚è—pƒXƒŒƒbƒh

        string getID(string input)
        {
            string id = "";
            id = input;

            
            //ShowP(mainW);

            //if (input == "-6148914691236517206")
            //{
            //    id = "Hello Gartheepan";
            //}
            //else if (input == "-2459565876494606883")
            //{
            //    id = "Hello Arthur";
            //}
            //else if (input == "131555511")
            //{
            //    id = "Hello Vince";
            //}
          

            return id;
        }

        void ReadIdWorker()
        {
            byte[] rxBytes = new byte[DefaultBufferSize];

            RFIDDataRx dataRx;
            dataRx = new RFIDDataRx();

            while (true)
            {
                if (!rfid.IsOpen)
                {
                    Console.WriteLine("RFID not opened. ");
                    break;
                }

                if (rfid.ReceiveMessage(ref rxBytes, ref dataRx))
                {
                    if (dataRx.id == RFIDComm.RX_ID_OTHER_READ)
                    {
                        if (Debug == true)
                        {
                            Console.WriteLine("Received Bytes:{0}" + BitConverter.ToString(ChopBytes(rxBytes)));
                        }
                        //if(lastId != -1)
                        //{
                        //textBoxId.Text = "Error";
                        //DealEvent(0);
                        //	lastId = -1;
                        //}
                    }
                    else if (dataRx.id == RFIDComm.RX_ID_NO_READ)
                    {
                        if (Debug == true)
                        {
                            Console.WriteLine("No Read");
                        }

                        if (lastId != 0)
                        {
                            if (removeFlag)
                            {
                                //textBoxId.Text = "No Read";
                                DealEvent(0);
                                lastId = 0;
                            }
                        }
                    }
                    else
                    {
                        string typeStr;
                        switch (dataRx.type)
                        {
                            case RFIDComm.RX_TYPE_RO:
                                typeStr = "Read Only";
                                break;
                            case RFIDComm.RX_TYPE_RW:
                                typeStr = "Read/Write";
                                break;
                            case RFIDComm.RX_TYPE_MPT:
                                typeStr = "MPT";
                                break;
                            default:
                                typeStr = "Other";
                                break;
                        }

                        if (Debug == true)
                        {
                            Console.WriteLine("Succeed: " + typeStr + dataRx.id);
                        }

                        if (dataRx.id != lastId)
                        {
                            string input;
                            input = getID(dataRx.id.ToString());
                            if (input != "")
                            {
                                // furniture items
                                if( input == "163175544" || input == "163130604" || input == "-6148914691236517206"){
                                    if(WinRef is MainWindow){
                                        MainWindow temp = WinRef as MainWindow;

                                        if( input == "163175544" ){
                                            temp.Dispatcher.BeginInvoke(ShowP, temp, "HOPEN");
                                        }
                                        else if (input == "163130604")
                                        {
                                            temp.Dispatcher.BeginInvoke(ShowP, temp, "STOCKHOLM");
                                        }
                                        else if (input == "-6148914691236517206")
                                        {
                                            temp.Dispatcher.BeginInvoke(ShowP, temp, "NORRSTEN");

                                        }

                                    }
                                }
                                //member login
                                else if(input == "163130613" || input == "163175535" || input == "163175525"){
                                    if(WinRef is Window3){
                                        Window3 temp = WinRef as Window3;
                                        if (input == "163130613")
                                        {
                                            temp.Dispatcher.BeginInvoke(ShowMemberP, temp, "Arthur Chow");
                                        }
                                        else if (input == "163175535")
                                        {
                                            temp.Dispatcher.BeginInvoke(ShowMemberP, temp, "Vince Chang");
                                        }
                                        else if (input == "163175525")
                                        {
                                            temp.Dispatcher.BeginInvoke(ShowMemberP, temp, "Gartheepan R");
                                        }

                                    }
                                }

                                //if (input == "-6148914691236517206")
                                //{
                                //    id = "Hello Gartheepan";
                                //}
                                //else if (input == "-2459565876494606883")
                                //{
                                //    id = "Hello Arthur";
                                //}
                                //else if (input == "131555511")
                                //{
                                //    id = "Hello Vince";
                                //}

                            
                              
                              //  MessageBox.Show(getID(dataRx.id.ToString()));
                            }
                            
                            
                            //textBoxId.Text = dataRx.id.ToString();
                            //MessageBox.Show("ID read: " + dataRx.id.ToString());
                            //MessageBox.Show( );
                            //CODE HERE //unique id read
                            //Create command here for when id is read (any id) need to check which user
                            Console.WriteLine("RFID id read: " + dataRx.id.ToString());
                            //DealEvent(dataRx.id);
                            lastId = dataRx.id;
                        }

                    }
                }
                else
                {
                    Console.WriteLine("Same ID card is in proximity, so not read.");
                    
                }
                Thread.Sleep(200);
            }
            return;
        }
        #endregion

    }
}
